package com.ruoyi.framework.config;


import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.access.expression.ExpressionUtils;

/**
 * spring security spel测试
 */
public class SpelTest {
    public static void main(String[] args) {
        test1();
        test2();
    }

    /**
     * 默认变量方式，需要带#号
     */
    public static void test1(){
        ExpressionParser parser = new SpelExpressionParser();
        // 使用直接量表达式l
        Expression exp = parser.parseExpression("#authenticated");
        StandardEvaluationContext ctx = new StandardEvaluationContext();
        // 设置变量
        ctx.setVariable("authenticated" , true);
        boolean b = ExpressionUtils.evaluateAsBoolean(exp,ctx);
        System.out.println(b);
    }

    /**
     * spring security 实现方式，访问根对象的方法
     */
    public static void test2(){
        ExpressionParser parser = new SpelExpressionParser();
        // 使用直接量表达式l
        Expression exp = parser.parseExpression("authenticated");
        StandardEvaluationContext ctx = new StandardEvaluationContext();
        // 设置rootobject
        ctx.setRootObject(new Ob());
        boolean b = ExpressionUtils.evaluateAsBoolean(exp,ctx);
        System.out.println(b);
    }
}
class Ob{
    public final boolean isAuthenticated() {
        return true;
    }
}